package com.vayne.thread;

/**
 * @author xuerui.zhang
 * @since 2020/4/25 下午7:40
 */
public class SynchronizeMorePointDemo {

    public static void main(String[] args) throws InterruptedException {
        MorePointService service = new MorePointService();
        new ThreadA(service).start();
        Thread.sleep(1_000);
        new ThreadB(service).start();
        System.out.println("send stop command");
    }
}

class MorePointService {
    private boolean flag = true;

    // FIXME 为什么这里能起作用？
    private Object monitor = new Object();

    public void run() {
        while (flag) {
            synchronized (monitor) {

            }
        }
        System.out.println("stop");
    }

    public void stop() {
        flag = false;
    }
}

class ThreadA extends Thread {

    private MorePointService service;

    public ThreadA(MorePointService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.run();
    }
}

class ThreadB extends Thread {

    private MorePointService service;

    public ThreadB(MorePointService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.stop();
    }
}